/*
* jQuery dropdown plugin base on Autocompleter 
*
* Copyright (c) 2009 Jörn Zaefferer
*
* Dual licensed under the MIT and GPL licenses:
*   http://www.opensource.org/licenses/mit-license.php
*   http://www.gnu.org/licenses/gpl.html
*
* Revision: $Id: jquery.dropdown.js 15 2009-08-22 10:30:27Z joern.zaefferer $
*/

; (function ($) {
    var defaults = {
        inputClass: 'ac_input',
        inputActiveClass: 'ac_input_active',
        resultsClass: "ac_results",
        loadingClass: "ac_loading",
        disabledClass: 'ac_disabled',
        minChars: 1,
        delay: 400,
        matchCase: false,
        matchSubset: true,
        matchContains: 'word',
        cacheLength: 10,
        max: 5000,
        maxCache: null,
        mustMatch: false,
        extraParams: {},
        selectFirst: true,
        selectedValue: false,
        /*Function*/
        formatDisplayItem: null,
        formatItem: function (row) {
            if (typeof row == 'string')
                return row;
            if (row['text'])
                return row['text'];

            return typeof row;
        },
        /*
        * Value to pass to server when submit
        */
        formatValue: function (row) {
            if (row && row['value'])
                return row.value;
            if (row != undefined && typeof (row) === 'object') {
                for (var i in row) {
                    return row[i];
                }
            }
            return row;
        },
        formatHeader: null,
        onChanged: null, // Occured after the item is changed
        onBeforeHide: null, // Occured before the dropdown hide
        onHide: null, // Occured after the dropdown hide
        onUnAutoComplete: null,
        onBeforeOpen: null, // Occured before the dropdown open
        formatMatch: null,
        autoFill: false,
        width: 0,
        height: 20,
        //
        // The width of box which contains results. It's value can be:
        // - { false: The width will get with as width of input width }
        // - { 'auto': The width will auto expand as the with of it's content }
        // - { Number: Sepcify a width of box content }
        //
        boxWidth: false,
        allowInput: false, // User can type text into textbox to search value
        multiple: false,
        multipleSeparator: ", ",
        highlight: function (value, term) {
            return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
        },
        scroll: true,
        waterMark: 'Type to search...',
        autoHeight: false, // If autoHeight is set to TRUE, scrollHeight will be ignored
        //autoWidth: false,
        scrollHeight: 180,
        showItemOnSelect: false // Use just when "allowInput" is TRUE
    };

    var dropdownArr = [];
    function unAutoComplete(id) {
        if (!id)
            return;
        var index = -1;
        $.each(dropdownArr, function (i, input) {
            if (input.id == id) {
                index = i;
                return false;
            }
        });

        if (index > -1) {
            var api = $.data(dropdownArr[index], 'dropdown');
            api && api.unautocomplete();
            dropdownArr.splice(index, 1);
        }
    };

    $.fn.extend({
        dropdown: function (urlOrData, options) {
            var isUrl = typeof urlOrData == "string";
            options = $.extend({}, defaults, {
                url: isUrl ? urlOrData : null,
                data: isUrl ? null : urlOrData,
                delay: isUrl ? defaults.delay : 10,
                isUrl: isUrl
                //max: options && !options.scroll ? 10 : 150
            }, options);

            // if highlight is set to false, replace it with a do-nothing function
            options.highlight = options.highlight || function (value) { return value; };

            // if the formatMatch option is not specified, then use formatItem for backwards compatibility
            options.formatMatch = options.formatMatch || options.formatItem;

            options.formatDisplayItem = options.formatDisplayItem || options.formatItem;

            return this.each(function () {
                unAutoComplete(this.id);
                new $.Autocompleter(this, options);
            });
        }
    });

    $.Autocompleter = function (input, options) {
        var dropdownAPI = this;
        var KEY = {
            UP: 38,
            DOWN: 40,
            DEL: 46,
            TAB: 9,
            RETURN: 13,
            ESC: 27,
            COMMA: 188,
            PAGEUP: 33,
            PAGEDOWN: 34,
            BACKSPACE: 8,
            CTRL: 17,
            SHIFT: 16,
            ALT: 18
        };
        //
        // <div>
        //		<div class="dropdown-item">
        //			<table>
        //				<td>
        //					<div class="dropdown-item-text">Item</div>
        //				</td>
        //				<td>
        //					<img src="Arrow" class="dropdown-arrow" />
        //				</td>
        //			</table>
        //		</div>
        //		<div style="height:1px;overflow:hidden;position: relative;top:-100px">
        //			<input type="text" style="border:none;" />
        //		</div>
        // </div>
        //
        var inputWrapperHtml = [
			'<div class="dropdown-item">',
				'<table class="dropdown-item-table" style="width:100%;height:', options.height || 20, 'px" cellpadding="0" cellspacing="0">',
					'<td valign="middle">',
						'<div class="dropdown-td-text">',
							'<div class="dropdown-item-text padding-l-2 padding-left-5">&nbsp;</div>',
						'</div>',
					'</td>',
					'<td valign="top">',
					    '<a href="javscript;" class="arrow-wrapper" tabIndex="-1">',
						    '<img src="' + (sPLDomain + 'Content/images/') + 'blank.gif" class="ac-arrow" tabIndex="-1" />',
						'</a>',
					'</td>',
				'</table>',
			'</div>',
			'<div class="hidden-wrapper" style="height:1px;overflow:hidden;position:relative;top:-100px;">',
			'</div>'
		];
        // Create $ object for input element
        var $input = $(input).attr("autocomplete", "off").css({ border: 'none', 'outline-color': 'white' }).wrap('<div/>');
        var $wrapper = $input.parent(),
			width = options.width > 0 ? options.width : options.minWidth,
			height = options.height || 20;
        if (!width)
            width = 100;

        var inputpadding = 2,
			dropdownWidth = width + inputpadding * 2;

        $wrapper
			.append(inputWrapperHtml.join(''))
			.addClass(options.inputClass)
			.css({
			    'width': 'auto',
			    'overflow': 'hidden',
			    'display': 'inline-block'
			});
        if ($.browser.msie) {
            $wrapper.css({
                width: width
            });
        }
        var $hiddenWrapper = $wrapper.find('.hidden-wrapper'),
			$itemWrapper = $wrapper.find('.dropdown-item'), // Use to diplay dropdown selected item
			$itemOuter = $itemWrapper.find('.dropdown-td-text'),
			$text = $wrapper.find('.dropdown-item-text').css('cursor', 'default'),
			$arrow = $wrapper.find('.arrow-wrapper');

        if (options.allowInput && options.isUrl)
            $arrow.find('.ac-arrow').addClass('ac-arrow-search');
        else if (options.allowInput) {
            $arrow.find('.ac-arrow').addClass('ac-arrow-both');
        }

        var arrowWidth = $arrow.find('.ac-arrow').first().css('height', height + 'px').width() + 2;
        var textAreaWith = width - arrowWidth - 2;

        $arrow.css({
            'height': height + 2 + 'px',
            'line-height': height + 'px',
            'display': 'block',
            'width': arrowWidth + 'px',
            'vertical-align': 'middle',
            'padding-left': '2px'
        }).focus(function (e) {
            if (!$wrapper.hasClass(options.inputActiveClass))
                $wrapper.addClass(options.inputActiveClass);
        });

        $arrow.closest('td').css('width', arrowWidth + 'px');
        //var inputWidth = dropdownWidth - (inputpadding * 2) - $arrow.width();

        $itemWrapper.css({ width: width + 'px', height: height + 'px', 'line-height': height + 'px' });

        /*var padding = '';
        if ($.browser.msie) {
            padding = '0px 1px';
        } else {
            padding = '0px 1px';
        }*/


        $itemOuter.css({
            /*'width': textAreaWith + 'px',
            'height': height + 'px',
            'line-height': height + 'px',*/
            'padding': '0px 1px'

        })
        .closest('td').css('width', (width - arrowWidth) + 'px');

        $input.css({
            'width': (textAreaWith - 2) + 'px',
            'height': (height) + 'px',
            'line-height': (height) + 'px'
        });

        $input.detach().appendTo($hiddenWrapper);
        if (options.allowInput) {
            $input.detach().appendTo($itemOuter);
            $text.hide();
        }

        var timeout, hideTimeout;
        var previousValue = "";
        var cache = $.Autocompleter.Cache(options);
        var hasFocus = 0;
        var lastKeyPressCode;
        var isBusy = false;
        var mouseOverInput = false;
        var isTextBoxClicked = false;
        var isMaskFilled = false;
        var config = {
            mouseDownOnSelect: false
        };
        var select = $.Autocompleter.Select(options, input, selectCurrent, config);
        select.init();
        var blockSubmit;

        // prevent form submit in opera when selecting with return key
        $.browser.opera && $(input.form).bind("submit.autocomplete", function () {
            if (blockSubmit) {
                blockSubmit = false;
                return false;
            }
        });

        // only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all
        $input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function (event) {
            // a keypress means the input has focus
            // avoids issue where input had focus before the autocomplete was applied
            hasFocus = 1;

            // track last key pressed
            lastKeyPressCode = event.keyCode;
            switch (event.keyCode) {
                case KEY.UP:
                    event.preventDefault();
                    if (select.visible()) {
                        select.prev();
                    } else {
                        onChange(0, true);
                    }
                    break;

                case KEY.DOWN:
                    event.preventDefault();
                    if (select.visible()) {
                        select.next();
                    } else {
                        onChange(0, true);
                    }
                    break;

                case KEY.PAGEUP:
                    event.preventDefault();
                    if (select.visible()) {
                        select.pageUp();
                    } else {
                        onChange(0, true);
                    }
                    break;

                case KEY.PAGEDOWN:
                    event.preventDefault();
                    if (select.visible()) {
                        select.pageDown();
                    } else {
                        onChange(0, true);
                    }
                    break;
                case KEY.TAB:
                case KEY.RETURN:
                    hasFocus = 0;
                    select.onEnter();
                    if (selectCurrent()) {
                        // stop default to prevent a form submit, Opera needs special handling
                        event.preventDefault();
                        blockSubmit = true;
                        return false;
                    }
                    break;

                case KEY.ESC:
                    //$input.trigger('blur');
                    hideResults();
                    break;
                case KEY.CTRL:
                case KEY.ALT:
                case KEY.SHIFT:
                    break;
                default:
                    //clearWaterMark();
                    clearTimeout(timeout);
                    timeout = setTimeout(onChange, options.delay);
                    break;
            }
        }).focus(function () {
            // track whether the field has focus, we shouldn't process any
            // results if the field no longer has focus
            hasFocus++;
            if (!$wrapper.hasClass(options.inputActiveClass))
                $wrapper.addClass(options.inputActiveClass);
        }).blur(function () {
            hasFocus = 0;
            isTextBoxClicked = false;
            if ($wrapper.hasClass(options.inputActiveClass))
                $wrapper.removeClass(options.inputActiveClass);
        }).click(function (e) {
            isTextBoxClicked = true;
        });



        function isDropdown(target) {
            if ($(target).hasClass(options.inputClass))
                return true;
            else {
                return $(target).closest('.' + options.inputClass).size() > 0 || $(target).closest('.' + options.resultsClass).size() > 0;
            }
        };

        function hideAllBuThis(id) {
            $.each(dropdownArr, function (i, ctrl) {
                if (ctrl.id !== id) {
                    $.data(ctrl, 'dropdown') && $.data(ctrl, 'dropdown').hide();
                }
            });
        };

        $(document).bind('mouseup.' + $input.attr('id'), { inputId: $input.attr('id') }, function (e) {
            // Wtf with left mouse button on IE (e.button = 1)
            if (hasFocus == 0
                && (($.browser.msie && e.button === 1) || (e.button === 0))
                && !select.isMouseOver()) {
                if (hideTimeout)
                    clearTimeout(hideTimeout);
                hideTimeout = setTimeout(hideResultsNow, 100);
            } else {
                //hideAllBuThis(e.data.inputId);
            }
        });

        $(window).resize(function () {
            select.visible() && select.show();
        });
        //
        // Public functions
        function unautocomplete() {
            select.unbind();
            $input.unbind();
            $(input.form).unbind(".autocomplete");
        };
        function setOptions(opts) {
            $.extend(options, opts);
            // if we've updated the data, repopulate
            if ("data" in opts) {
                cache.populate();
                if (!options.allowInput || (options.allowInput && options.showItemOnSelect)) {
                    select.emptyList();
                    request('', fillOnFirstLoad);
                }
            }
        };
        function flushCache() {
            cache.flush();
        };
        function seach(handler) {
            // TODO why not just specifying both arguments?
            var fn = handler;
            function findValueCallback(q, data) {
                var result;
                if (data && data.length) {
                    for (var i = 0; i < data.length; i++) {
                        if (data[i].result.toLowerCase() == q.toLowerCase()) {
                            result = data[i];
                            break;
                        }
                    }
                }
                if (typeof fn == "function") fn(result);
                else $input.trigger("result", result && [result.data, result.value]);
            }
            $.each(trimWords($input.val()), function (i, value) {
                request(value, findValueCallback, hideResultsNow);
            });
        };

        function hideBusy() {
            if ($input.hasClass(options.loadingClass))
                $input.removeClass(options.loadingClass);
            $text.css('visibility', 'visible');
            if ($itemOuter.hasClass(options.loadingClass))
                $itemOuter.removeClass(options.loadingClass);
            isBusy = false;
        };

        function showBusy() {
            $input.addClass(options.loadingClass);
            $text.css('visibility', 'hidden');
            $itemOuter.addClass(options.loadingClass);
            isBusy = true;
        };

        function show() {
            if (!select.visible()) {
                if (hideTimeout)
                    clearTimeout(hideTimeout);

                if (!options.isUrl) {
                    if ($.browser.msie) {
                        $input[0].setActive();
                    }
                    $input.trigger('focus');
                }
                select.show();
                if (options.allowInput) {
                    var term = $.trim($input.val());
                    if (typeof term == 'string' && term.length > 0) {
                        setTimeout(function () {
                            request(term, receiveData);
                            if (options.selectFirst) {
                                var current = select.current();
                                if (!current) {
                                    select.pageUp();
                                }
                            }
                        }, 200);
                    }
                    else {
                        //modified: for the first time
                        if (options.allowInput) {
                            $text.hide();
                            $input.detach().appendTo($itemOuter);
                            if (!options.isUrl) {
                                if ($.browser.msie) {
                                    $input[0].setActive();
                                }
                                $input.trigger('focus');
                            }
                        }
                        //end modified
                        fillWaterMark();
                    }
                }
            }
        };

        function hide() {
            hideResultsNow();
        };

        function setSelected(value) {
            var data = cache.load('');
            // recieve the cached data
            if (data && data.length) {
                hideBusy();
                select.display(data, '');
                select.setSelected(value);
            }
        };

        if (options.allowInput && options.isUrl) {
            $input.detach().appendTo($itemOuter);
            $text.hide();
        }

        $itemWrapper.click(function (e) {
            e.preventDefault();
            if (isBusy)
                return;
            if (hideTimeout)
                clearTimeout(hideTimeout);
            if (!select.visible()) {
                //e.stopPropagation();
                if (options.allowInput) {
                    if ($.contains($hiddenWrapper[0], $input[0]) && !options.isUrl) {
                        $input.detach().appendTo($itemOuter);
                        //$text.detach().appendTo($hiddenWrapper);
                        $text.hide();
                    }
                    if (!options.isUrl) {// && ($(e.target).hasClass('arrow-wrapper') || $(e.target).hasClass('ac-arrow'))) {
                        if (typeof options.onBeforeOpen == 'function') {
                            if (options.onBeforeOpen.call($input[0]) === false) {
                                return;
                            }
                        }

                        hasFocus = 1;
                        request('', receiveData, hideResultsNow);
                    }
                    if (!options.isUrl)
                        fillWaterMark();
                } else {
                    if (typeof options.onBeforeOpen == 'function') {
                        if (options.onBeforeOpen.call($input[0]) === false) {
                            return;
                        }
                    }
                    hasFocus = 1;
                    request('', receiveData, hideResultsNow);
                }

                // show select when clicking in a focused field
                if ($.browser.msie) {
                    $input[0].setActive();
                    // W-T-F with IE
                    setTimeout(function () {
                        $input[0].setActive();
                    }, 400);
                }
                $input.trigger('focus');
            } else {
                hideResultsNow();
            }
        }).hover(function (e) {
            mouseOverInput = true;
        }, function (e) {
            mouseOverInput = false;
        });

        function fillWaterMark() {
            var strWaterMark = ''; //$('.name-currency > div', $text).text();
            if (typeof (options.waterMark) === 'string') {
                strWaterMark = options.waterMark;
            } else if (typeof (options.waterMark) === 'function') {
                strWaterMark = options.waterMark.call({}, $text, $input);
                if (!strWaterMark) {
                    strWaterMark = '';
                }
            }
            $input.val(strWaterMark).selection(0, strWaterMark.length);
            isMaskFilled = true;
        };
        function clearWaterMark() {
            if (isMaskFilled) {
                $input.val('');
                isMaskFilled = false;
            }
        };

        function selectCurrent(isFirstLoaded) {
            var selected = select.selected();
            if (!selected)
                return false;

            var v = selected.value;

            if (v) {
                $text.html(selected.text);
                if (!isFirstLoaded) {
                    hideResultsNow();
                    if (typeof options.onChanged == "function" && previousValue !== v)
                        options.onChanged.call($input[0], selected.data, selected.result);
                    //$input.trigger("result", [selected.data, selected.result]);
                }
                previousValue = v;
            }
            return true;
        }


        function onChange(crap, skipPrevCheck) {
            if (lastKeyPressCode == KEY.DEL) {
                select.hide();
                return;
            }

            var currentValue = options.allowInput ? $input.val() : '';
            if (!options.allowInput) {
                var term = $input.val();
                if (term && term.length > 0) {
                    if (select.visible()) {
                        var data = cache.findFirstMatch(term);
                        if (data != null)
                            select.scrollToView(data.result);
                    }
                    $input.val('');
                }
            }
            if (!skipPrevCheck && currentValue == previousValue)
                return;
            if (typeof options.onBeforeOpen == 'function') {
                if (options.onBeforeOpen.call($input[0]) === false) {
                    return;
                }
            }
            previousValue = currentValue;

            currentValue = lastWord(currentValue);
            showBusy();
            if (currentValue.length >= options.minChars) {
                if (!options.matchCase)
                    currentValue = currentValue.toLowerCase();
                request(currentValue, receiveData, hideResultsNow);

                //if(select.current().length &&select.current().length)
            } else {
                hideBusy();
                select.hide();
            }
        };

        function trimWords(value) {
            if (!value)
                return [""];
            if (!options.multiple)
                return [$.trim(value)];
            return $.map(value.split(options.multipleSeparator), function (word) {
                return $.trim(value).length ? $.trim(word) : null;
            });
        }

        function lastWord(value) {
            if (!options.multiple)
                return value;
            var words = trimWords(value);
            if (words.length == 1)
                return words[0];
            var cursorAt = $(input).selection().start;
            if (cursorAt == value.length) {
                words = trimWords(value)
            } else {
                words = trimWords(value.replace(value.substring(cursorAt), ""));
            }
            return words[words.length - 1];
        }

        // fills in the input box w/the first match (assumed to be the best match)
        // q: the term entered
        // sValue: the first matching result
        function autoFill(q, sValue) {
            // autofill in the complete box w/the first match as long as the user hasn't entered in more data
            // if the last user key pressed was backspace, don't autofill
            if (options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE) {
                // fill in the value (keep the case the user has typed)
                $input.val($input.val() + sValue.substring(lastWord(previousValue).length));
                // select the portion of the value not typed by the user (so the next character will erase)
                $(input).selection(previousValue.length, previousValue.length + sValue.length);
            }
        };

        function hideResults() {
            clearTimeout(timeout);
            timeout = setTimeout(hideResultsNow, 200);
        };

        function hideResultsNow() {
            if (typeof options.onBeforeHide == 'function') {
                if (options.onBeforeHide.call($input[0]) === false) {
                    return;
                }
            }
            var wasVisible = select.visible();
            wasVisible && select.hide();
            if (timeout)
                clearTimeout(timeout);
            hideBusy();
            if (options.mustMatch) {
                // call search and run callback
                seach(
				function (result) {
				    // if no value found, clear the input box
				    if (!result) {
				        if (options.multiple) {
				            var words = trimWords($input.val()).slice(0, -1);
				            $input.val(words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : ""));
				        }
				        else {
				            $input.val("");
				            if (typeof options.onChanged == "function")
				                options.onChanged.call($input[0], null, null);
				        }
				    }
				}
			);
            }

            if (hasFocus == 0 && (!options.allowInput || (options.allowInput && !options.isUrl))) {
                //$text.detach().appendTo($itemOuter);
                !$text.is(':visible') && $text.show();
                if (!$.contains($hiddenWrapper[0], $input[0])) {
                    $input.detach().appendTo($hiddenWrapper);
                }
                //$input.trigger('blur');
            }
        };

        function receiveData(q, data) {
            if (data && data.length && hasFocus) {
                hideBusy();
                select.display(data, q);
                autoFill(q, data[0].value);
                select.show();
                if (options.allowInput && options.selectFirst) {
                    var current = select.current();
                    if (!current) {
                        select.pageUp();
                    }
                }
            } else {
                hideResultsNow();
            }
        };

        function fillOnFirstLoad(q, data) {
            hideBusy();
            if (data && data.length) {
                if (!options.allowInput || (options.allowInput && options.showItemOnSelect)) {
                    select.display(data, q);
                    if (options.allowInput && options.showItemOnSelect)
                        hideResultsNow();
                }
            } else {
                hideResultsNow();
            }
        };

        function request(term, success, failure) {
            if (!options.matchCase)
                term = term.toLowerCase();
            var data = cache.load(term);
            // recieve the cached data
            if (data && data.length) {
                success(term, data);
                // if an AJAX url has been supplied, try loading the data now
            } else if ((typeof options.url == "string") && (options.url.length > 0)) {

                var extraParams = {
                    timestamp: +new Date()
                };
                $.each(options.extraParams, function (key, param) {
                    extraParams[key] = typeof param == "function" ? param() : param;
                });

                $.ajax({
                    // try to leverage ajaxQueue plugin to abort previous requests
                    mode: "abort",
                    // limit abortion to this input
                    port: "autocomplete" + input.name,
                    dataType: options.dataType,
                    url: options.url,
                    data: $.extend({
                        q: lastWord(term),
                        limit: options.max
                    }, extraParams),
                    success: function (data) {
                        var parsed = options.parse && options.parse(data) || parse(data);
                        cache.add(term, parsed);
                        success(term, parsed);
                    }
                });
            } else {
                // if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match
                select.emptyList();
                failure && failure(term);
            }
        };

        function parse(data) {
            var parsed = [];
            if (typeof data === 'string') {
                var rows = data.split("\n");
                for (var i = 0; i < rows.length; i++) {
                    var row = $.trim(rows[i]);
                    if (row) {
                        row = row.split("|");
                        parsed[parsed.length] = {
                            data: row,
                            value: row[0],
                            result: options.formatValue && options.formatValue(row, row[0]) || row[0]
                        };
                    }
                }
            } else if ($.isArray(data)) {
                for (var i = 0, len = data.length; i < len; i++) {
                    var value = options.formatMatch(data[i], i + 1, data.length);
                    parsed.push({
                        data: data[i],
                        value: value,
                        result: options.formatValue && options.formatValue(data[i]) || value
                    });
                }
            }
            return parsed;
        };

        // Public API
        $.extend(dropdownAPI, {
            unautocomplete: function () {
                unautocomplete();
            },
            setOptions: function (opts) {
                setOptions(opts);
            },
            flushCache: function () {
                flushCache();
            },
            search: function (handler) {
                seach(handler);
            },
            hideBusy: function () {
                hideBusy();
            },
            showBusy: function () {
                showBusy();
            },
            show: function () {
                show();
            },
            hide: function () {
                hide();
            },
            setSelected: function (value) {
                setSelected(value);
            }
        });

        // End public functions

        $.data($input[0], 'dropdown', dropdownAPI);
        dropdownArr.push($input[0]);

        //if (!options.allowInput)
        setTimeout(function () {
            request('', fillOnFirstLoad);
            if ($.browser.msie) {
                $wrapper.css({
                    height: $wrapper.children('.dropdown-item').first().height()
                });
            }
        }, 200);
    };

    $.Autocompleter.Cache = function (options) {

        var data = {};
        var keys = [];
        var length = 0;
        var samePressedCharacterCount = -1; // Count the times of the same key which is pressed
        var lastPressedCharacter = '';

        function matchSubset(s, sub) {
            if (!options.matchCase)
                s = s.toLowerCase();
            if (options.allowInput) {
                if (typeof options.matchContains === 'function') {
                    return options.matchContains(s, sub);
                }
            }
            var i = s.indexOf(sub);
            if (options.matchContains == "word") {
                i = s.toLowerCase().search("\\b" + sub.toLowerCase());
            }

            if (i == -1) return false;
            return i == 0;
        };

        function add(q, value) {
            if (length > options.cacheLength) {
                flush();
            }
            if (!data[q]) {
                length++;
            }
            data[q] = value;
        }

        function populate() {
            if (!options.data) return false;
            // track the matches
            var stMatchSets = {}, nullData = 0;
            keys = [];
            // no url was specified, we need to adjust the cache length to make sure it fits the local data store
            if (!options.url) options.cacheLength = 1;

            // track all options for minChars = 0
            stMatchSets[""] = [];

            // loop through the array and create a lookup structure
            for (var i = 0, ol = options.data.length; i < ol; i++) {
                var rawValue = options.data[i];
                // if rawValue is a string, make an array otherwise just reference the array
                rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue;
                var disabled = (typeof rawValue != "string") && rawValue.disabled === true;
                if (!options.allowInput) {
                    var value = options.formatMatch(rawValue, i + 1, options.data.length);
                    var text = options.formatDisplayItem(rawValue);
                    if (value === false)
                        continue;

                    stMatchSets[""].push({
                        value: value,
                        data: rawValue,
                        result: options.formatValue && options.formatValue(rawValue) || value,
                        disabled: disabled,
                        text: text
                    });
                }
                else {
                    var value = options.formatMatch(rawValue, i + 1, options.data.length);
                    var text = options.formatDisplayItem(rawValue);
                    if (value === false)
                        continue;

                    var firstChar = value.charAt(0).toLowerCase();
                    // if no lookup array for this character exists, look it up now
                    if (!stMatchSets[firstChar])
                        stMatchSets[firstChar] = [];

                    // if the match is a string
                    var row = {
                        value: value,
                        data: rawValue,
                        result: options.formatValue && options.formatValue(rawValue) || value,
                        disabled: disabled,
                        text: text
                    };

                    // push the current match into the set list
                    stMatchSets[firstChar].push(row);

                    // keep track of minChars zero items
                    if (nullData++ < options.max) {
                        stMatchSets[""].push(row);
                    }
                }
            };

            // add the data items to the cache
            $.each(stMatchSets, function (i, value) {
                // increase the cache size
                options.cacheLength++;
                // add to the cache
                add(i, value);
                keys.push(i);
            });
        }

        // populate any existing data
        setTimeout(populate, 25);

        function flush() {
            data = {};
            length = 0;
            keys = [];
        }

        return {
            flush: flush,
            add: add,
            populate: populate,
            /**
            * TODO find the first match item. Use for dropdown list only (allowInput = false)
            * 
            */
            findFirstMatch: function (q) {
                if (options.allowInput) {
                    if (data[q])
                        return $.map(data[q], function (it) { return it; })
                    else
                        return null;
                }

                if (typeof (q) == 'string' && q.length > 0) {
                    q = q.substring(0, 1);
                    if (lastPressedCharacter !== q) {
                        samePressedCharacterCount = -1;
                        lastPressedCharacter = q;
                    }

                    var d = data[''],
                        len = d.length,
                        i = 0;
                    i = ++samePressedCharacterCount;
                    if (i == len - 1) {
                        i = 0;
                    }
                    for (; i < len; i++) {
                        if (d[i] && matchSubset(d[i].value, q)) {
                            samePressedCharacterCount = i;
                            return d[i];
                        }
                    }
                    lastPressedCharacter = '';
                    samePressedCharacterCount = -1;
                }
                return null;
            },
            load: function (q) {
                if (!options.cacheLength || !length)
                    return null;
                if (!options.allowInput) {
                    var csub = [];
                    var c = data[''];
                    $.each(c, function (i, x) {
                        csub.push(x);
                    });
                    return csub;
                }
                /* 
                * if dealing w/local data and matchContains than we must make sure
                * to loop through all the data collections looking for matches
                */
                if (!options.url && options.matchContains) {
                    // track all matches
                    var csub = [];
                    if (typeof q == 'string' && q.replace(/\s+/g, '').length <= 0) {
                        var c = data[''];
                        $.each(c, function (i, x) {
                            csub.push(x);
                        });
                    } else {
                        // loop through all the data grids for matches
                        for (var j = 0, len = keys.length; j < len; j++) {
                            // don't search through the stMatchSets[""] (minChars: 0) cache
                            // this prevents duplicates
                            var k = keys[j];
                            if (k.length > 0) {
                                var c = data[k];
                                if (c) {
                                    $.each(c, function (i, x) {
                                        // if we've got a match, add it to the array
                                        if (matchSubset(x.value, q)) {
                                            csub.push(x);
                                        }
                                    });
                                }
                            }
                        }
                    }
                    return csub;
                } else
                // if the exact item exists, use it
                    if (data[q]) {
                        return data[q];
                    } else
                        if (options.matchSubset) {
                            for (var i = q.length - 1; i >= options.minChars; i--) {
                                var c = data[q.substr(0, i)];
                                if (c) {
                                    var csub = [];
                                    $.each(c, function (i, x) {
                                        if (matchSubset(x.value, q)) {
                                            csub.push(x);
                                        }
                                    });
                                    return csub;
                                }
                            }
                        }
                return null;
            }
        };
    };

    $.Autocompleter.Select = function (options, input, select, config) {
        var CLASSES = {
            ACTIVE: "ac_over"
        };

        var listItems,
		active = -1,
		header = $('<div/>').addClass('ac_header'),
		data,
		term = "",
		needsInit = true,
		element,
		wrapper = $(input).closest('.' + options.inputClass),
		list,
		currentSelectedIndex = 0,
		selectedValue = options.selectedValue || false,
		selectedData = {},
		isFirstFill = true,
        isOver = false; // Track mouse is over the element

        // Create results
        function init() {
            if (!needsInit)
                return;
            element = $("<div/>")
			.hide()
			.addClass(options.resultsClass)
			.css("position", "absolute")
			.appendTo(document.body)
			.hover(function () {
			    isOver = true;
			}, function () {
			    isOver = false;
			    // Just forcus when dropdown is visible
			    if ($(this).is(":visible")) {
			        if ($.browser.msie) {
			            input.setActive();
			        }
			        $(input).trigger('focus');
			    }
			});
            element.find('.ac_header').first().remove();
            if (options.formatHeader && jQuery.isFunction(options.formatHeader)) {
                header
                    .appendTo(element)
                    .empty()
                    .append(options.formatHeader());
            }
            list = $("<ul/>").appendTo(element).mouseover(function (event) {
                var $li = target(event);
                if ($li.nodeName && $li.nodeName.toUpperCase() == 'LI') {
                    $li = $($li);
                    if (!$li.hasClass(options.disabledClass)) { // Ignore disabled item
                        active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event));
                        $li.addClass(CLASSES.ACTIVE);
                    }
                }
            }).click(function (event) {
                var $li = $(target(event));
                if (!$li.hasClass(options.disabledClass)) {// Ignore disabled item
                    $li.addClass(CLASSES.ACTIVE);
                    onEnter($li);
                    select();
                    // TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus
                    if (options.isUrl) {
                        if ($.browser.msie) {
                            input.setActive();
                        }
                        $(input).trigger('focus');
                    } else {
                        if ($.browser.msie) {
                            input.setActive(false);
                        }
                        $(input).trigger('blur');
                    }
                }
                return false;
            }).mousedown(function () {
                config.mouseDownOnSelect = true;
            }).mouseup(function () {
                config.mouseDownOnSelect = false;
            });

            if (options.boxWidth === 'auto')
                element.css("width", 'auto');
            else if (options.boxWidth > 0)
                element.css("width", options.boxWidth + 'px');
            else
                element.css("width", options.width);

            //needsInit = false;
        }

        function onEnter($li) {
            if (!$li) {
                $li = listItems && listItems.filter("." + CLASSES.ACTIVE).first();
            }
            if ($li && $li.length) {
                currentSelectedIndex = listItems.index($li);
                var d = $.data($li[0], "ac_data");
                if (d) {
                    selectedValue = d.result;
                    selectedData = d;
                }
            }
        };

        function isMouseOver() {
            return isOver;
        };

        function target(event) {
            var el = event.target;
            while (el && el.tagName != "LI")
                el = el.parentNode;
            // more fun with IE, sometimes event.target is empty, just ignore it then
            if (!el)
                return [];
            return el;
        }

        function moveSelect(step) {
            listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
            movePosition(step);
            if (listItems.slice(active, active + 1).hasClass(options.disabledClass)) {
                movePosition(step);
            }
            var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
            if (options.scroll && activeItem.length > 0) {
                var offset = 0;
                listItems.slice(0, active).each(function () {
                    offset += this.offsetHeight;
                });
                if ((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
                    list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
                } else if (offset < list.scrollTop()) {
                    list.scrollTop(offset);
                }
            }
        };

        function movePosition(step) {
            active += step;
            if (active < 0) {
                active = listItems.size() - 1;
            } else if (active >= listItems.size()) {
                active = 0;
            }
        }

        function limitNumberOfItems(available) {
            return options.max && options.max < available
			? options.max
			: available;
        }

        function fillList() {
            if (needsInit || options.allowInput) {
                list.empty();
                var max = limitNumberOfItems(data.length);
                for (var i = 0; i < max; i++) {
                    if (!data[i])
                        continue;

                    var formatted = options.formatItem(data[i].data, i + 1, max, data[i].value, term);
                    if (formatted === false)
                        continue;
                    var $li = $("<li/>").html(options.highlight(formatted, term)).addClass(i % 2 == 0 ? "ac_even" : "ac_odd").appendTo(list);
                    if (data[i].disabled === true)
                        $li.addClass(options.disabledClass);
                    var li = $li[0];
                    //if (!options.allowInput) {
                    if (selectedValue == data[i].result) {
                        currentSelectedIndex = i;
                    }
                    //}
                    $.data(li, "ac_data", data[i]);
                }
                needsInit = false;
                listItems = list.find("li");
                //if (!options.allowInput && currentSelectedIndex !== -1) {
                active = currentSelectedIndex;
                //}
            }

            //if (!options.allowInput) {
            if (currentSelectedIndex !== -1)
                active = currentSelectedIndex;
            if (active >= 0)
                listItems.removeClass(CLASSES.ACTIVE);
            //else
            //active = currentSelectedIndex = 0;
            if (active >= 0)
                listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
            if (active >= 0 && !options.allowInput || (options.allowInput && options.showItemOnSelect)) {
                // Just fill selected data at the first fill
                if (isFirstFill) {
                    onEnter();
                    select(true);
                    isFirstFill = false;
                }
            }

            //}

            //if (options.allowInput && options.selectFirst) {
            //listItems.slice(0, 1).addClass(CLASSES.ACTIVE);
            //active = 0;
            //}
            // apply bgiframe if available
            if ($.fn.bgiframe)
                list.bgiframe();
        };

        function setSelected(value) {
            if (!options.allowInput || (options.allowInput && options.showItemOnSelect)) {
                var hasItem = false;
                listItems.each(function (i) {
                    var d = $.data(this, 'ac_data');
                    if (d.result === value && d.disabled !== true) {
                        selectedValue = d.result;
                        currentSelectedIndex = i;
                        active = i;
                        hasItem = true;
                        return false;
                    }
                });
                if (hasItem) {
                    listItems.removeClass(CLASSES.ACTIVE);
                    var $li = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
                    onEnter($li);
                    select(true);
                }
            }
        };
        var hideTimeout = null;
        return {
            onEnter: onEnter,
            init: function () {
                init();
            },
            display: function (d, q) {
                //init();
                data = d;
                term = q;
                fillList();
            },
            isMouseOver: function () {
                return isMouseOver();
            },
            next: function () {
                moveSelect(1);
            },
            prev: function () {
                moveSelect(-1);
            },
            pageUp: function () {
                if (active != 0 && active - 8 < 0) {
                    moveSelect(-active);
                } else {
                    moveSelect(-8);
                }
            },
            pageDown: function () {
                if (active != listItems.size() - 1 && active + 8 > listItems.size()) {
                    moveSelect(listItems.size() - 1 - active);
                } else {
                    moveSelect(8);
                }
            },
            hide: function () {
                wrapper.removeClass(options.inputActiveClass);
                element && element.hide();
                if (options.allowInput) {
                    listItems && listItems.removeClass(CLASSES.ACTIVE);
                    active = -1;
                }
                if ($.isFunction(options.onHide)) {
                    options.onHide();
                }
            },
            visible: function () {
                return element && element.is(":visible");
            },
            current: function () {
                return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0]/* || options.selectFirst && listItems[0]*/);
            },
            reposition: function () {
                if (!element.is(':visible'))
                    return;
                var offset = wrapper.offset();
                element.css({
                    top: offset.top + wrapper.outerHeight(),
                    left: offset.left - w
                });
            },
            show: function () {
                if (!wrapper.hasClass(options.inputActiveClass))
                    wrapper.addClass(options.inputActiveClass);
                var offset = wrapper.offset();
                var width = '';
                if (options.boxWidth === 'auto')
                    width = 'auto';
                else if (options.boxWidth > 0)
                    width = options.boxWidth;
                else
                    width = wrapper.width();
                var wrapperWidth = wrapper.width();
                var w = 0;
                if (width > wrapperWidth) {
                    var dir = '';
                    $.each(['html', 'body'], function () {
                        dir = $(String(this)).attr('dir');
                        if (typeof dir == 'string' && dir.length > 0) {
                            dir = dir.toLowerCase();
                            return false;
                        }
                    });
                    if (typeof dir == 'string' && dir.length > 0 && dir == 'rtl') {
                        w = width - wrapperWidth;
                    }
                }
                element.css({
                    width: width,
                    top: offset.top + wrapper.outerHeight(),
                    left: offset.left - w
                }).show();

                if (options.scroll && !options.autoHeight) {
                    list.scrollTop(0);
                    var height = 0;
                    listItems.each(function () {
                        height += this.offsetHeight;
                    });
                    height = height >= options.scrollHeight ? options.scrollHeight : height;
                    list.css({
                        maxHeight: height + 'px',
                        overflow: 'auto'
                    });

                    if ($.browser.msie && document.body.style.maxHeight == '') {
                        var listHeight = 0;
                        listItems.each(function () {
                            listHeight += this.offsetHeight;
                        });
                        var scrollbarsVisible = listHeight > options.scrollHeight;
                        list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight);
                        if (!scrollbarsVisible) {
                            // IE doesn't recalculate width when scrollbar disappears
                            //listItems.width(list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")));
                        }
                    }

                }
                //if (!options.allowInput) {
                var offset = 0,
					activeItem = listItems.slice(active, active + 1);
                listItems.slice(0, active).each(function () {
                    offset += this.offsetHeight;
                });
                if (activeItem.size() > 0) {
                    if ((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
                        list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
                    } else if (offset < list.scrollTop()) {
                        list.scrollTop(offset);
                    }
                }
                //}
            },
            /**
            * TODO scroll the scroller to particular item. 
            * Just use for drodown list mode (allowInput = false)
            * @param {String} toValue The value of item that scroller will scroll to
            */
            scrollToView: function (value) {
                if (!options.allowInput) {
                    var itemIndex = -1;
                    listItems.each(function (i) {
                        var d = $.data(this, 'ac_data');
                        if (d.result === value && d.disabled !== true) {
                            itemIndex = i;
                            return false;
                        }
                    });
                    if (itemIndex > -1 && this.visible()) {
                        var offset = 0,
					        activeItem = listItems.slice(itemIndex, itemIndex + 1);
                        listItems.slice(0, itemIndex).each(function () {
                            offset += this.offsetHeight;
                        });
                        if (activeItem.size() > 0) {
                            if ((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
                                list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
                            } else if (offset < list.scrollTop()) {
                                list.scrollTop(offset);
                            }
                            listItems && listItems.removeClass(CLASSES.ACTIVE);
                            activeItem.addClass(CLASSES.ACTIVE);
                            active = itemIndex;
                        }

                    }
                }
            },
            selected: function () {
                return selectedData;
            },
            setSelected: setSelected,
            emptyList: function () {
                list && list.empty();
                needsInit = true;
            },
            unbind: function () {
                element && element.remove();
                if ($.isFunction(options.onUnAutoComplete)) {
                    options.onUnAutoComplete();
                }
            }
        };
    };

    $.fn.selection = function (start, end) {
        if (start !== undefined) {
            return this.each(function () {
                if (this.createTextRange) {
                    var selRange = this.createTextRange();
                    if (end === undefined || start == end) {
                        selRange.move("character", start);
                        selRange.select();
                    } else {
                        selRange.collapse(true);
                        selRange.moveStart("character", start);
                        selRange.moveEnd("character", end);
                        selRange.select();
                    }
                } else if (this.setSelectionRange) {
                    this.setSelectionRange(start, end);
                } else if (this.selectionStart) {
                    this.selectionStart = start;
                    this.selectionEnd = end;
                }
            });
        }
        var field = this[0];
        if (field.createTextRange) {
            var range = document.selection.createRange(),
			orig = field.value,
			teststring = "<->",
			textLength = range.text.length;
            range.text = teststring;
            var caretAt = field.value.indexOf(teststring);
            field.value = orig;
            this.selection(caretAt, caretAt + textLength);
            return {
                start: caretAt,
                end: caretAt + textLength
            }
        } else if (field.selectionStart !== undefined) {
            return {
                start: field.selectionStart,
                end: field.selectionEnd
            }
        }
    };
})(jQuery);